package com.sinog.biz.service.business.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinog.biz.mapper.havexml.AbAnzhiMapper;
import com.sinog.biz.mapper.havexml.AbPrisonerMapper;
import com.sinog.biz.mapper.havexml.PlacementBaseInfoMapper;
import com.sinog.biz.mapper.havexml.ReleaseHelpEduMapper;
import com.sinog.biz.service.business.ReleaseHelpEduService;
import com.sinog.biz.util.ConditionUtils;
import com.sinog.biz.util.IdGen;
import com.sinog.biz.util.smlib.Sm4;
import com.sinog.core.domain.AbPrisonersJcab;
import com.sinog.core.domain.PlacementBaseInfo;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.util.PageReturnUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @desc 安置帮教管理 - 解除安置帮教管理
 * @author dangyf
 * @date 2020年2月17日 13点12分
 */
@Service
@Slf4j
public class ReleaseHelpEduServiceImpl extends ServiceImpl<ReleaseHelpEduMapper,AbPrisonersJcab> implements ReleaseHelpEduService {

    @Resource
    private ReleaseHelpEduMapper releaseHelpEduMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AbPrisonerMapper abPrisonerMapper;
    @Autowired
    private PlacementBaseInfoMapper placementBaseInfoMapper;
    @Autowired
    private AbAnzhiMapper abAnzhiMapper;

    /**
     * 安置帮教管理 - 解除帮教管理 - 列表
     * @param searchMap 查询条件（关键字：姓名）
     * @param pageIndex 起始值
     * @param pageSize 条数
     * @return String
     */
    @Override
    public String getReleaseHelpEduList(Map<String,Object> searchMap,Integer pageIndex,Integer pageSize) {
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        //身份证搜索条件加密
        if(ObjectUtils.isNotEmpty(searchMap.get("shenKey"))) {
            searchMap.put("shenKey",Sm4.encryptEcb(searchMap.get("shenKey").toString()));
        }
        //其他条件不为空将其拆分数组后转换为list集合
        List<String> qitaKey = null;
        String qitaKeyStr = (String)searchMap.get("qitaKey");
        if(StringUtils.isNotBlank(qitaKeyStr)) {
            String[] split = qitaKeyStr.split(",");
            qitaKey = Arrays.asList(split);
        }
        searchMap.put("qitaKey",qitaKey);
        //分页查询
        if ("releaseDate".equals(searchMap.get("sortField"))){
            //如果是按照解除时间排序
            //审核状态为未申请和已申请但审批失败的，按照解除时间升序排序
            List<Map<String, String>> list2 = abPrisonerMapper.getReleaseHelpEduList1(page, searchMap);
            //已申请并且是审批中和审批通过的
            List<Map<String, String>> list1 = abPrisonerMapper.getReleaseHelpEduList2(page, searchMap);
            if (Constants.Number.NUM_ZERO == list2.size()){
                list1.addAll(list2);
                page.setTotal(list1.size());
                page = page.setRecords(list1);
            } else {
                list2.addAll(list1);
                page.setTotal(list2.size());
                page = page.setRecords(list2);
            }
        }else {
            page = page.setRecords(abPrisonerMapper.getReleaseHelpEduList(page,searchMap));
        }
        searchMap.put("total",page.getTotal());

        CompletableFuture.runAsync(() -> {
            log.info("工作台-解除帮教管理-异步条件进入redis {}:"+Thread.currentThread().getName());
            ConditionUtils.searchConditions(searchMap,searchMap.get("account").toString(),redisTemplate);
        });
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 安置帮教管理 - 解除帮教管理 - 申请解除帮教
     * @param data 保存的数据信息
     * @return Result
     */
    @Override
    public Result save(String data) {
        //参数转换封装map
        Map<String,Object> dataMap = JsonUtil.toMap(data);
        dataMap.put("pid",String.valueOf(dataMap.get("priNum")));
        dataMap.put("jiechu_reason",String.valueOf(dataMap.get("releaseReason")));
        dataMap.put("jiechu_remark",String.valueOf(dataMap.get("releaseRemark")));
        dataMap.put("jiechu_date",dataMap.get("releaseDate"));
        dataMap.put("adduserid",String.valueOf(dataMap.get("clab")));
        dataMap.put("addusername",String.valueOf(dataMap.get("clab_name")));
        dataMap.put("superiorid",String.valueOf(dataMap.get("orgid")));
        String newData = JsonUtil.toText(dataMap);
        //参数实体
        AbPrisonersJcab abPrisonersJcab = JsonUtil.toBean(newData,AbPrisonersJcab.class);
        //新增
        Date date = new Date();
        if(StringUtils.isBlank(abPrisonersJcab.getId())) {
            abPrisonersJcab.setId(IdGen.strid());
            abPrisonersJcab.setCreateTime(date);
        }
        abPrisonersJcab.setUpdateTime(date);
        abPrisonersJcab.setUpdateUser(abPrisonersJcab.getCreateUser());
        //入库
        boolean insertOrUpdateResult = abPrisonersJcab.insertOrUpdate();
        if(insertOrUpdateResult) {
            return Result.success("保存成功");
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 安置帮教管理 - 解除帮教管理 - 保存审批解除安置帮教（修改/新增）
     * @param data data
     * @param loginAccount loginAccount
     * @return Result
     */
    @Override
    public Result saveAuditing(String data,String loginAccount) {
        //参数实体
        AbPrisonersJcab abPrisonersJcab = JsonUtil.toBean(data,AbPrisonersJcab.class);
        abPrisonersJcab.setUpdateUser(loginAccount);
        abPrisonersJcab.setUpdateTime(new Date());
        if(Constants.NumberStr.NUM_STR_THREE.equals(abPrisonersJcab.getSpzt())) {
            abPrisonersJcab.setFailurContent(Constants.HnInterfaceDocking.AGREE);
            String priNum = abPrisonersJcab.getPriNum();
            // 司法局审批通过后将基地的安置人数-1,历史安置人数+1
            List<Map<String,String>> jds = abAnzhiMapper.searchAnzhiJd(priNum);
            if(0 < jds.size()) {
                jds.forEach(e -> {
                    String jdId = e.get(Constants.StrFinalValue.JDID);
                    if(!StringUtils.isEmpty(jdId)) {
                        //获取安置基地的数量
                        Integer num = placementBaseInfoMapper.getJdKeAnZhiNum(jdId);
                        placementBaseInfoMapper.changeJdNum(e.get("jdid"),--num);
                        //修改历史安置人数
                        PlacementBaseInfo placementBaseInfo = new PlacementBaseInfo();
                        PlacementBaseInfo placement = placementBaseInfo.selectById(jdId);
                        if(placement != null) {
                            int lsAnzhi = Integer.parseInt(null == placement.getLsAnzhirenshu() ? "0" : placement.getLsAnzhirenshu());
                            placement.setLsAnzhirenshu(String.valueOf(++lsAnzhi));
                            placement.updateById();
                        }
                    }
                });
            }
        }
        abPrisonersJcab.setCreateUser(null);
        boolean tag = abPrisonersJcab.updateById();
        if(tag) {
            return Result.success("保存成功");
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 安置帮教管理 - 解除帮教管理 -查看审核失败原因
     * @param priNum priNum
     * @return String
     */
    @Override
    public String getAuditResult(String priNum) {
        return releaseHelpEduMapper.getAuditResult(priNum);
    }
}